﻿using System.IO;
using System.Threading.Tasks;
using ChildPhotosManager.Core.Services;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace ChildPhotosManager.Web.Controllers;

public class DownloadController : Controller
{
    private readonly IPhotoService _photoService;
    private readonly IWebHostEnvironment _webHostEnv;
    private readonly IConfiguration _configuration;

    public DownloadController(IPhotoService photoService, IWebHostEnvironment webHostEnv, IConfiguration configuration)
    {
        _photoService = photoService;
        _webHostEnv = webHostEnv;
        _configuration = configuration;
    }

    /// <summary>
    /// 下载照片
    /// </summary>
    [Route("Download")]
    public async Task<IActionResult> Index(int id)
    {
        var photo = await _photoService.GetPhotoByIdAsync(id);
        if (photo == null) return NotFound("照片不存在");

        var photoRootPath = _configuration["FileStorage:PhotoRootPath"] ?? Path.Combine(_webHostEnv.ContentRootPath, "wwwroot", "uploads");
        var fullPath = Path.Combine(photoRootPath, photo.StoredFileName);

        if (!System.IO.File.Exists(fullPath)) return NotFound("照片文件已丢失");

        var fileBytes = await System.IO.File.ReadAllBytesAsync(fullPath);
        return File(fileBytes, photo.ContentType, photo.FileName);
    }
}